package com.tina.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * sh命令执行
 * @author Tina
 * @version 1.0
 * @since 2021/11/19 09:29
 **/
public class XshellUtil {

    /**
     * 执行命令并返回
     * @param cmd
     * @return
     */
    public static StringBuilder sh(String cmd) {
        // 读取输出 result是shell中的输出
        StringBuilder result = new StringBuilder();
        try {
            String[] params = new String[]{"/bin/sh", "-c", cmd};
            Process ps = Runtime.getRuntime().exec(params);
            ps.waitFor();

            BufferedReader bufrIn = new BufferedReader(new InputStreamReader(ps.getInputStream(), "UTF-8"));
            BufferedReader bufrError = new BufferedReader(new InputStreamReader(ps.getErrorStream(), "UTF-8"));
            String line = null;
            while ((line = bufrIn.readLine()) != null || (line = bufrError.readLine()) != null) {
                result.append(line).append('\n');
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.append(e.getMessage());
        }
        return result;
    }
}
